<template>
    <a-drawer :width="openType == 'literalTitle' ? 600 : 800" :maskClosable="false" v-model:visible="visible"
        @close="onClose" class="custom-class" title="风险词检测" placement="right">
        <template #extra>
            <a-button type="primary" @click="customRiskTerm">自定义风险词</a-button>
        </template>
        <div class="content">
            <!-- 查询统计 -->
            <div class="statistics">
                <span>查询总数：{{ totalTextLength || '0' }}个字，共<span style="color: #FF4D4F;">{{ suggestionTotal
                    || '0' }}条</span>建议</span>
                <a-button type="link" @click="textFrobidden('retest')" :loading="retestLoading"><redo-outlined
                        v-if="!retestLoading" />重新检测</a-button>
            </div>
            <!-- 风险词列表 -->
            <div class="filtered_data" v-if="!spining">
                <div class="filtered_data_item" v-for="(ele, index) in filtered_data" :key="index">
                    <div class="hit_risk_words">
                        <div class="risk_title"
                            style="background:linear-gradient(to right,#eeeeee , rgba(255, 87, 51, 0));color: var(--ss-primary-color);">
                            * 风险词
                        </div>
                        <div class="type_risk_list">
                            <p class="hit_risk" style="color: #FF4D4F;font-weight: 600;"
                                v-if="ele.hit_risk_words.high_risk.length">
                                <span>高风险：</span>
                                <span v-for="(hit_risk, i) in ele.hit_risk_words.high_risk">
                                    <template v-if="index < ele.hit_risk_words.high_risk.length - 1">
                                        {{ hit_risk }}、
                                    </template>
                                    <template v-else>
                                        {{ hit_risk }}
                                    </template>
                                </span>
                            </p>
                            <p class="medium_risk" style="color:#FAAD14;font-weight: 600;"
                                v-if="ele.hit_risk_words.medium_risk.length">
                                <span>中风险：</span>
                                <span v-for="(medium_risk, i) in ele.hit_risk_words.medium_risk">
                                    <template v-if="index < ele.hit_risk_words.medium_risk.length - 1">
                                        {{ medium_risk }}、
                                    </template>
                                    <template v-else>
                                        {{ medium_risk }}
                                    </template>
                                </span>
                            </p>
                            <p class="low_risk" v-if="ele.hit_risk_words.low_risk.length"
                                style="color:#55C51F;font-weight: 600;">
                                <span>低风险：</span>
                                <span v-for="(low_risk, index) in ele.hit_risk_words.low_risk">
                                    <template v-if="index < ele.hit_risk_words.low_risk.length - 1">
                                        {{ low_risk }}、
                                    </template>
                                    <template v-else>
                                        {{ low_risk }}
                                    </template>
                                </span>
                            </p>
                            <p class="custom_risk" v-if="ele.hit_risk_words.custom_risk.length"
                                style="color:#bcb8fe;font-weight: 600;">
                                <span>自定义风险：</span>
                                <span v-for="(custom_risk, index) in ele.hit_risk_words.custom_risk">
                                    <template v-if="index < ele.hit_risk_words.custom_risk.length - 1">
                                        {{ custom_risk }}、
                                    </template>
                                    <template v-else>
                                        {{ custom_risk }}
                                    </template>
                                </span>
                            </p>
                            <p class="text">
                                <span v-if="openType == 'script_scenes'" style="margin-right: 3px;">台词:</span>
                                <span v-if="openType == 'textEditing'" style="margin-right: 3px;">字幕: </span>
                                <span v-if="openType == 'literalTitle'" style="margin-right: 3px;">标题: </span>
                                <span v-if="openType == 'release_title'" style="margin-right: 3px;">标题: </span>
                                <span v-html="highlightText(ele)"></span>
                            </p>
                        </div>
                    </div>
                </div>
                <!-- 空状态 -->
                <template v-if="riskWordList?.every(item => item.risk_text.length <= 0)">
                    <a-empty :image="simpleImage" />
                </template>
            </div>
            <!-- 加载 -->
            <div v-else class="spin-box">
                <a-spin :spinning="spining" size="large"></a-spin>
            </div>
        </div>
        <template #footer>
            <a-button type="primary" @click="onClose">关闭</a-button>
        </template>
    </a-drawer>
    <EditRiskModal :visible="editRiskVisible" :sensitiveInfo="sensitiveInfo" @close="closeRiskEdit" />
</template>

<script>
import {
    defineComponent,
    reactive,
    toRefs,
    computed,
    watch,
    nextTick,
    ref,
    onMounted,
    createVNode,
} from "vue";
import { useRouter, useRoute } from "vue-router";
import request from "@/common/utils/request";
import { RedoOutlined } from '@ant-design/icons-vue'
import { Empty, message } from 'ant-design-vue';
// id生成
import { nanoid } from "nanoid";
// 自定义风险词
import EditRiskModal from '../../../MatrixMarketing/modules/editRiskModal.vue';
export default defineComponent({
    components: {
        RedoOutlined,
        EditRiskModal
    },
    setup() {
        const state = reactive({
            visible: false,
            textArr: [],//要检测的文本
            filtered_data: [],//风险词列表
            spining: true,//页面加载
            totalTextLength: 0,//总字数长度
            suggestionTotal: 0,//建议总数
            editRiskVisible: false,
            sensitiveInfo: {},//自定义风险词
            retestLoading: false,
            openType: ''//打开弹窗类型
        })
        const router = useRouter();
        const route = useRoute();
        const showDrawer = (data, openType) => {
            console.log(openType)
            state.visible = true;
            state.textArr = data
            state.openType = openType
            state.totalTextLength = state.textArr.reduce((acc, str) => {
                const cleanedStr = str.replace(/\s+/g, ''); // 去除所有空格和换行符
                return acc + cleanedStr.length; // 累加每个字符串去空格和换行符后的长度
            }, 0);
            textFrobidden()//开启风险词检测
        };
        const textFrobidden = (type) => {
            initData()
            state.spining = true
            // 重新检测
            if (type == 'retest') {
                state.retestLoading = true
            }
            request.post("/work_ai", "/user/shotstack/banned/check", { text: state.textArr.filter(ele => ele.trim().length > 0) }).then(res => {
                let riskData = res.result
                state.filtered_data = riskData.filtered_data.map(ele => {
                    return {
                        hit_risk_words: {
                            custom_risk: ele.hit_risk_words.custom_risk ? Object.keys(ele.hit_risk_words.custom_risk) : [],
                            high_risk: ele.hit_risk_words.high_risk ? Object.keys(ele.hit_risk_words.high_risk) : [],
                            medium_risk: ele.hit_risk_words.medium_risk ? Object.keys(ele.hit_risk_words.medium_risk) : [],
                            low_risk: ele.hit_risk_words.low_risk ? Object.keys(ele.hit_risk_words.low_risk) : [],
                        },
                        text: ele.text
                    }
                })
                state.suggestionTotal = state.filtered_data.length
            }).catch(err => {
                message.error('查询失败，请点击重新查询')
                state.spining = false
                state.retestLoading = false//开启重新检测加载
            }).finally(() => {
                state.spining = false
                state.retestLoading = false
            })
        }
        // 自定义风险词
        const customRiskTerm = () => {
            state.sensitiveInfo = {}
            state.editRiskVisible = true
        }
        const onClose = () => {
            state.visible = false;
            initData()
        };
        // 初始化数据
        const initData = () => {
            state.filtered_data = []
        }
        const closeRiskEdit = () => {
            state.sensitiveInfo = {}
            state.editRiskVisible = false
        }
        const highlightText = (info) => {
            let highlightedText = info.text;
            const high_risk_keywords = info.hit_risk_words.high_risk
            const medium_risk_keywords = info.hit_risk_words.medium_risk
            const low_risk_keywords = info.hit_risk_words.low_risk
            const custom_risk_keywords = info.hit_risk_words.custom_risk
            // 自定义风险词
            if (custom_risk_keywords.length) {
                custom_risk_keywords.forEach(tag => {
                    const regex = new RegExp(`(${tag})`, 'g');
                    highlightedText = highlightedText.replace(regex, `<span style="text-decoration: none; box-shadow: inset 0 -1px 0 0 #5C53FF;'">\$1</span>`);
                });
            }
            // 低风险词
            if (low_risk_keywords.length) {
                low_risk_keywords.forEach(tag => {
                    const regex = new RegExp(`(${tag})`, 'g');
                    highlightedText = highlightedText.replace(regex, `<span style="text-decoration: none; box-shadow: inset 0 -1px 0 0 #55C51F;">\$1</span>`);
                });
            }
            // 中风险词
            if (medium_risk_keywords.length) {
                medium_risk_keywords.forEach(tag => {
                    const regex = new RegExp(`(${tag})`, 'g');
                    highlightedText = highlightedText.replace(regex, `<span style="text-decoration: none; box-shadow: inset 0 -1px 0 0 #FAAD14;">\$1</span>`);
                });
            }
            // 高风险词
            if (high_risk_keywords.length) {
                high_risk_keywords.forEach(tag => {
                    const regex = new RegExp(`(${tag})`, 'g');
                    highlightedText = highlightedText.replace(regex, `<span style="text-decoration: none; box-shadow: inset 0 -1px 0 0 #FF4D4F;">\$1</span>`);
                });
            }

            return highlightedText;
        }
        return {
            ...toRefs(state),
            showDrawer,
            customRiskTerm,
            onClose,
            router,
            route,
            simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
            textFrobidden,
            closeRiskEdit,
            highlightText
        }
    }
})
</script>

<style lang="less" scoped>
.content {

    // 查询统计
    .statistics {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    // 敏感词列表
    .filtered_data {
        max-height: 700px;
        overflow-y: auto;
        padding-right: 10px;

        &::-webkit-scrollbar {
            width: 8px;
            /* 滚动条的宽度 */
            height: 10px;
            /* 滚动条的高度，垂直滚动条可能用得上 */
            // display: none;
        }

        &::-webkit-scrollbar-thumb {
            background: #eeeeee;
            /* 滑块的背景颜色 */
            border-radius: 10px;
            /* 滑块的圆角 */

        }

        // 风险词每一项
        .filtered_data_item {
            margin-top: 10px;
            flex: 1;

            .hit_risk_words {
                border: 1px solid #dde2e9;
                border-radius: 10px;

                .risk_title {
                    line-height: 30px;
                    font-weight: 900;
                    padding-left: 10px;
                    border-radius: 10px 10px 0 0;
                }

                .type_risk_list {
                    margin-top: 10px;
                    padding-left: 10px;
                    font-weight: 600;

                    .text {
                        color: #bac0cb;
                    }
                }
            }
        }


    }

    .spin-box {
        width: 100%;
        display: flex;
        justify-content: center;
        margin-top: 100px;
    }
}
</style>